/*
 * @Autor: lingchen.liu
 * @Date: 2022-02-10 17:13:21
 * @LastEditors: lingchen.liu
 * @LastEditTime: 2022-02-11 10:18:37
 * @emial: lingchen.liu@bizfocus.cn
 */
import React, { FC, ReactElement, useRef } from "react";
import Modal from "..";
import { ITodo } from "../../../types";
import './index.scss';

interface IEditModal {
    isShowEditModal: boolean,
    data: ITodo,
    submitEdit: (newData: ITodo, id: number) => ITodo
}

const EditModal: FC<IEditModal> = ({ isShowEditModal, data, submitEdit }): ReactElement => {

    const { id } = data;

    const inputRef: any = useRef<HTMLInputElement>();
    const checkRef: any = useRef<HTMLInputElement>();

    const formatNewData = (() => {
        // 对编辑框中的数据处理：使用trim清除前后的空格
        const inputLen = inputRef.current.value.trim().length;

        // 如果没有输入值，则把原来的数据填充
        if (inputLen === 0) {
            inputRef.current.value = data.content;
            return;
        }
        // 否则新建newData 把修改的数据保存到newData中
        const newData = {
            id: new Date().getTime(),
            content: inputRef.current.value,
            completed: checkRef.current.checked,
        }
        // 编辑完成后提交，拿到原来的id
        submitEdit(newData, id);
    })
    return (
        <Modal isShowModal={isShowEditModal} modalTitle="编辑事件">
            <p className="topic">时间：{data.id}</p>
            <p className="topic">
                <textarea
                    className="text-area"
                    ref={inputRef}
                    defaultValue={data.content}
                ></textarea>
            </p>
            <p className="topic">
                状态：
                <input
                    className="edit-input"
                    type="checkbox"
                    defaultChecked={data.completed ? true : false}
                    ref={checkRef}
                />
            </p>
            <button className="btn btn-primary confirm-btn" onClick={formatNewData}>
                确定
            </button>
        </Modal>
    )
}

export default EditModal

